--
-- Author: yawei.zhu
-- Date: 2018-08-07 15:31:48
--
-- RoadHeroChallengeView
--
local IconRender = require("app.widget.renders.IconRender")
local AvatarIconNode = require("app.widget.AvatarIconNode")
local NewRareInfoView = require("app.newBag.views.NewRareInfoView")


local fileName = string.getModeName(...)
local ClassRef = class(fileName, app.mvc.ViewBase)

ClassRef.VIEW_ROOT_RES = Res.RoadHeroScene

local NUM_COUNT = 3

function ClassRef:init()

	display.nodeRemoveForNotHit(self._ui.Panel, function()
		-- executeFunc(self._onCloseView, self)
		self:closeView()
	end)

	self._ui.Button_hero:addClickEventListener(function()
		if self:checkCanEnter() then
			self:showSkillNotice()
			executeFunc(self._onOperate, "reqChallenge", self._indexID)
		end
	end)

	self._ui.Button_queding:addClickEventListener(function()
		self:hide(function()
			executeFunc(self._onOperate, "reqRoadOfHeroOpenBox", self._level)
			executeFunc(self._onCloseView, self)
		end)
	end)
	self._ui["Button_queding/name"]:setString( L("task_road_desc4") )

	self._ui.Button_3:addClickEventListener(function()
		self:showRareInfo(self._level, self._step)
	end)

	self._panelHero = self._ui.Panel_hero
	self._box = self._ui.icon_1
	self._panelReward = self._ui.Panel_reward
end

function ClassRef:checkCanEnter()
	-- 判断是否有队伍，并且队伍里是否只有我自己
	local TeamModel = app:getInst("TeamModel")

	if TeamModel:isInTeam() and TeamModel:getMemberNum() > 1 then
		display.pushToast(L("ErrRoadOfHeroTeam2"))
		return false
	end
	-- 判断当前是否在地图边界
	local mapInfo = GD:getHeroRoadMapBorder(MapManager:getMapId())
	if mapInfo then
		local posX = FieldManager:getCharacterX()
		local borders = string.split(mapInfo.mapExtent, ";")
		for _, border in ipairs(borders) do
			local seg = string.split(border, "|")
			local left = tonumber(seg[1])
			local right = tonumber(seg[2])
			if posX >= left and posX <= right then
				display.pushToast(L("ErrRoadOfHeroMap"))
				return false
			end
		end
	end

	return true
end

function ClassRef:showSkillNotice()
	local myChooseID = UD:getCurSpecTypeId()
	local needChooseID = tonumber(self._config.spec_typeID)
	-- typeID为0时，不弹出提示
	if needChooseID == 0 then
		return
	end

	-- 先判断专精是否一致
	if myChooseID ~= needChooseID then
		display.pushToast(L("task_road_desc5"))
	else
		-- 再判断技能是否已选
		local skillIds = GD:getTeachSkillIds(tonumber(self._config.classId))
		local teamIds = UD:getSkillChoose().teamIds
		for _, skillId in ipairs(skillIds) do
			local bFind = false
			for _, id in ipairs(teamIds) do
				if tonumber(id) == tonumber(skillId) then
					bFind = true
					break
				end
			end
			if bFind == false then 
				display.pushToast(L("task_road_desc6"))
				break
			end
		end
	end
end

-- 设置左右翻页按钮
function ClassRef:setPageBtn(level, step, process)
	local btnL = self._ui.Button_1
	local btnR = self._ui.Button_2

	local preLevel, preStep = 0, 0
	local nextLevel, nextStep = 0, 0

	-- 前一个节点
	if level == 1 and step == 1 then
		btnL:setVisible(false)
	end

	if step > 1 then
		preLevel = level
		preStep = step - 1
	else
		preLevel = level - 1
		preStep = NUM_COUNT
	end

	function pointIsExit(level, step)
		if GD:getHeroInfoByIndex(nextLevel, nextStep) then
			return true
		end
		return false
	end

	-- 后一个节点
	if step >= NUM_COUNT then
		nextLevel = level + 1
		nextStep = 1
		if not pointIsExit() then
			btnR:setVisible(false)
		end
	else
		nextLevel = level
		nextStep = step + 1
	end 

	-- 添加监听事件
	btnL:addClickEventListener(function()
		self:showChallenge(preLevel, preStep, process)
	end)
	btnR:addClickEventListener(function()
		self:showChallenge(nextLevel, nextStep, process)
	end)
end

function ClassRef:showChallenge(level, step, process)
	self:clearChallengeView()

	self._ui.Button_1:setVisible(true)
	self._ui.Button_2:setVisible(true)
	self._panelHero:setVisible(true)
	-- self._ui.Button_3:setVisible(true)

	self._level = level
	self._step = step

	self:setPageBtn(level, step, process)

	self._ui.tlt:setString( string.format( L("task_road_desc8"), level, step) ) 

	self._ui["Panel_reward/tlt_2"]:setString( L("task_road_desc7") )
	display.setNodesMiddle(self._ui.Panel_reward, self._ui["Panel_reward/img"], self._ui["Panel_reward/tlt_2"])

	-- 自己
	local myPanel = self._panelHero:getChildByName("Panel_my")
	local iconNode = AvatarIconNode.new(myPanel, "icon")
	iconNode:update(UD:getAvatarParams())
	myPanel:getChildByName("name"):setString( UD:getNickName() )

	local panelNum = myPanel:getChildByName("Panel_num")
	panelNum:setVisible(true)
	local sp = panelNum:getChildByName("icon")
	local num = panelNum:getChildByName("num")
	num:setString( UD:getCombatPower() )
	num:setColor( cc.c3b(0xFF, 0xFF, 0xFF) )
	display.setNodesMiddle(panelNum, nil, sp, num)

	-- 对手
	local config = GD:getHeroInfoByIndex(level, step, UD:getClass())
	self._indexID = tonumber(config.ID)
	self._config = config

	local enemyPanel = self._panelHero:getChildByName("Panel_foe")
	enemyPanel:getChildByName("icon"):loadTexture(Res.npcIconPath .. config.icon .. ".png")
	enemyPanel:getChildByName("name"):setString( L(config.bnpcName) )

	-- 携带技能
	local txtNotice = self._panelHero:getChildByName("tips")
	txtNotice:setString("")

	if self._richText then
		self._richText:removeFromParent()
		self._richText = nil
	end

	if config.teachID then
		if tonumber(config.spec_typeID) == 0 then
			txtNotice:setString(L(config.teachID))
		else
			local defaults = {
    		    KEY_FONT_FACE = Res.font,
    		    KEY_FONT_SIZE = 18,
    		    KEY_FONT_COLOR_STRING = "#FFE184",
    		}
    		local str1 = display.getRichTextFontXml( string.format("%s", L(config.teachID)), "#77deff", 18)
   			local str = string.format( L("task_road_desc9"), str1)
		
    		local richText = ccui.RichText:createWithXML( str, defaults )
    		richText:ignoreContentAdaptWithSize( true )
    		-- richText:setWrapMode( 1 )
    		richText:formatText()
    		richText:setPosition( txtNotice:getPosition() )
    		richText:addTo(self._panelHero)
    		self._richText = richText
		end
	end

	local panelNum2 = enemyPanel:getChildByName("Panel_num")
	panelNum2:setVisible(true)
	local sp2 = panelNum2:getChildByName("icon")
	local num2 = panelNum2:getChildByName("num")
	num2:setString(config.powerNeed)
	display.setNodesMiddle(panelNum2, nil, sp2, num2)

	if process:checkIsPass(level, step) then -- 已通关
		self._ui.Button_hero:setVisible(true)
		if tonumber(config.spec_typeID) ~= 0 then
			panelNum:setVisible(false)
			panelNum2:setVisible(false)
		end
		for i = 1, NUM_COUNT do
			self._ui.Panel_reward:getChildByName("icon_"..i):setVisible(false)
		end
		self._ui["Panel_reward/text"]:setString( L("task_road_desc10") )
		self._ui["Panel_reward/img"]:setVisible(false)
		self._ui["Panel_reward/tlt_2"]:setVisible(false)
	else
		if process:checkIsNext(level, step) then -- next
			if UD:getLevel() >= tonumber(config.level) then
				self._ui.Button_hero:setVisible(true)
			else
				self._ui.tips:setVisible(true)
				self._ui.tips:setString( string.format( L("task_road_desc11"), tonumber(config.level) ) )
			end
		else
			self._ui.tips:setVisible(true)
		end

		-- 显示战力颜色
		if tonumber(UD:getCombatPower()) < tonumber(config.powerNeed) then
			num:setColor( cc.c3b(0xFF, 0x40, 0x27) )
		else
			num:setColor( cc.c3b(117, 211, 124) )
		end

		-- 显示奖励
		local strAward = UD:parseClassText(config.award)
		local arrDrops = UD:parseDropStrToBagItem(strAward, true)
		for i, data in ipairs(arrDrops) do
			local icon = self._ui["Panel_reward/icon_"..i]
			local render = IconRender.create(icon)
			render:setData(arrDrops[i])
			render:setTipEnable(true)
		end
		-- 显示奖励提示
		self._ui["Panel_reward/img"]:setVisible(true)
		self._ui["Panel_reward/tlt_2"]:setVisible(true)
	end

end

function ClassRef:showBox(level, process)
	self:clearChallengeView()
	self._box:setVisible(true)

	self._level = level

	self._ui["Panel_reward/tlt_2"]:setString( L("task_road_desc12") )
	display.setNodesMiddle(self._ui.Panel_reward, self._ui["Panel_reward/img"], self._ui["Panel_reward/tlt_2"])

	self._ui.tlt:setString( L("task_road_desc2") )
	local config = GD:queryBoxInfoByLevel(level)
	-- 显示奖励
	local strAward = UD:parseClassText(config.award)
	local arrDrops = UD:parseDropStrToBagItem(strAward, true)
	for i, data in ipairs(arrDrops) do
		local icon = self._ui["Panel_reward/icon_"..i]
		local render = IconRender.create(icon)
		render:setData(arrDrops[i])
		render:setTipEnable(true)
	end

	-- 当前层是否已全部通关
	if process:checkHeroLevelIsPass(level) then
		self._box:getChildByName("tlt_1"):setString( L("task_road_desc13") )
		self._box:getChildByName("icon_lock"):setVisible(false)
		self._ui.Button_queding:setVisible(true)
	else
		self._box:getChildByName("tlt_1"):setString("")
		self._box:getChildByName("icon_lock"):setVisible(true)
		self._ui.tips:setVisible(true)
	end

	-- 延迟播放宝箱的动画
	self:runAction( cc.Sequence:create(cc.DelayTime:create(1.0), cc.CallFunc:create(function()
		self:playAction("animation", true)
	end)) )

end

function ClassRef:clearChallengeView()
	self._panelHero:setVisible(false)
	self._box:setVisible(false)

	self._ui.tips:setString( L("task_road_desc14") )
	self._ui.tips:setVisible(false)
	self._ui.Button_queding:setVisible(false)
	self._ui.Button_hero:setVisible(false)

	self._ui.Button_1:setVisible(false)
	self._ui.Button_2:setVisible(false)
	self._ui.Button_3:setVisible(false)

	self._ui["Panel_reward/text"]:setVisible(true)
	self._ui["Panel_reward/text"]:setString("")

	self._ui["Panel_reward/icon_1"]:setVisible(true)
	self._ui["Panel_reward/icon_2"]:setVisible(true)
	self._ui["Panel_reward/icon_3"]:setVisible(true)
end

function ClassRef:showRareInfo(level, step)
	local config = GD:getHeroInfoByIndex(level, step, UD:getClass())
	local dataTemp = {}
	dataTemp.name = string.format( L("task_road_desc8"), level, step)
	dataTemp.string1 = config.help
	dataTemp.string3 = L("task_road_desc15") .. config.teachID

	local rarePanel = NewRareInfoView.create()
	rarePanel:setData( dataTemp )
	-- self._ui["Panel"]:addChild( self._rareInfoPanel )
	UIHandler:addPopupUi(rarePanel)

	-- 点击空白区域关闭
	display.nodeRemoveForNotHit(rarePanel, function()
		rarePanel:removeFromParent()
	end)

	local triggerNodeBoundingBox = self._ui.Button_3:getBoundingBox()
	local worldPosTemp = self._ui.Panel:convertToWorldSpace( cc.p(triggerNodeBoundingBox.x, triggerNodeBoundingBox.y) )
	triggerNodeBoundingBox.x = worldPosTemp.x
	triggerNodeBoundingBox.y = worldPosTemp.y
	display.adjustNodePos( triggerNodeBoundingBox, rarePanel )
end

return ClassRef
